package com.cloud.salon.gateway.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.sql.Timestamp;
import java.util.Date;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.security.core.userdetails.UserDetails;

public class TokenAuthenticationUtil {
	
	static final long EXPIRATIONTIME = 432_000_000;     // 5天
    static final String SECRET = "P@ssw02d";            // JWT密码
    static final String TOKEN_PREFIX = "Bearer";        // Token前缀
    static final String HEADER_STRING = "Authorization";// 存放Token的Header Key

    /*
     * @Description JWT生成方法
     * @Author wolf--LZH
     */
    public static String generateToken(UserDetails userinfo) {
    	
    	String auth = userinfo.getAuthorities().toString().replace("[", "").replace("]", "");
    	
    	// 生成JWT
    	String JWT = Jwts.builder()
                // 保存权限（角色）
                .claim("authorities", auth)
                // 用户名写入标题
                .setSubject(userinfo.getUsername())
                // 有效期设置
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATIONTIME * EXPIRATIONTIME))
                // 签名设置
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
    	
    	return JWT;
    }

    // JWT验证方法
    ////返回字符串数数组，第一个表示Token表示的用户名，第二个为该用户所具有的的权限
    public static String[] parseToken(HttpServletRequest request) {
    	// 从Header中拿到token
    	String token = request.getHeader(HEADER_STRING);

    	if (token != null) {
            // 解析 Token
            Claims claims = Jwts.parser()
                    // 验签
                    .setSigningKey(SECRET)
                    // 去掉 Bearer
                    .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
                    .getBody();

            // 拿用户名
            String user = claims.getSubject();

            // 获取权限
            String authorities = (String) claims.get("authorities");
            //List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList();
            
            String[] tokenInfo = {user, authorities};
            
            // 返回验证令牌
            return user != null ? tokenInfo: null;
        }
        return null;
    }

    public static String generateToken(Integer userId) {
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        String token = DigestUtils.md5Hex(String.valueOf(userId) + timestamp.getTime()) + getIdByTimeStampAndRandom();
        return token;
    }

    public static String getIdByTimeStampAndRandom() {
        return getIdByTimeStampAndRandom(6);
    }

    public static String getIdByTimeStampAndRandom(int digit) {
        if (digit < 0) return "";
        return String.valueOf(System.currentTimeMillis()) + getRandomString(digit);
    }

    public static String getRandomString(int length) { //length表示生成字符串的长度
        String base = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }
}